package com.uxhao.orderservice.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.util.ResponseChecker;
import com.alipay.easysdk.payment.common.models.AlipayTradeQueryResponse;
import com.alipay.easysdk.payment.facetoface.models.AlipayTradePrecreateResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.wxpay.sdk.WXPayUtil;
import com.uxhao.commonutils.constants.ResultCode;
import com.uxhao.commonutils.util.YamlAndPropertySourceFactory;
import com.uxhao.orderservice.constants.OrderPayType;
import com.uxhao.orderservice.constants.OrderStatus;
import com.uxhao.orderservice.entity.TOrder;
import com.uxhao.orderservice.entity.TPayLog;
import com.uxhao.orderservice.mapper.TPayLogMapper;
import com.uxhao.orderservice.service.TOrderService;
import com.uxhao.orderservice.service.TPayLogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.uxhao.orderservice.utils.ConstantPropertiesUtils;
import com.uxhao.orderservice.utils.HttpClient;
import com.uxhao.servicebase.exceptionhandler.QLLException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 支付日志表 服务实现类
 * </p>
 *
 * @author uxhao
 * @since 2022/01/22
 */
@Service
@PropertySource(value = {"classpath:dev-key.yml"},factory = YamlAndPropertySourceFactory.class)
public class TPayLogServiceImpl extends ServiceImpl<TPayLogMapper, TPayLog> implements TPayLogService {

    @Autowired
    private TOrderService orderService;

    //支付成功后要跳转的页面
    @Value("${alipay.returnUrl}")
    private String returnUrl;
    /**
     *  根据订单号生成二维码
     * @param orderNo 订单号
     * @return
     */
    @Override
    public Map<String,Object> createNative(String orderNo) {
        try {
            //根据订单id获取订单信息
            QueryWrapper<TOrder> wrapper = new QueryWrapper<>();
            wrapper.eq("order_no",orderNo);
            TOrder order = orderService.getOne(wrapper);

            Map<String,String> m = new HashMap();
            //1、设置支付参数
            m.put("appid", ConstantPropertiesUtils.PAY_APPID);//关联的公众号appid
            m.put("mch_id", ConstantPropertiesUtils.PAY_PARTNER);//商户号
            m.put("nonce_str", WXPayUtil.generateNonceStr());//sdk 生成随机字符串 生成二维码最终不一样
            m.put("body", order.getCourseTitle());//订单中的商品名
            m.put("out_trade_no", orderNo);
            m.put("total_fee", order.getTotalFee().multiply(new BigDecimal("100")).longValue()+"");//价格转为字符串
            m.put("spbill_create_ip", "127.0.0.1");//终端IP 或域名
            m.put("notify_url", ConstantPropertiesUtils.PAY_NOTIFYURL);
            m.put("trade_type", "NATIVE");//交易类型

            //开发文档 https://pay.weixin.qq.com/wiki/doc/api/native.php?chapter=9_1
            //2、HTTPClient来根据URL访问第三方接口并且传递参数
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");

            //client设置参数
            client.setXmlParam(WXPayUtil.generateSignedXml(m, ConstantPropertiesUtils.PAY_PARTNERKEY));//商户key 加密参数转为xml
            client.setHttps(true);
            client.post();//发送请求
            //3、返回第三方的数据
            String xml = client.getContent();//xml格式
            System.out.println(xml);
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);//sdk xml转为map

            //4、封装返回结果集 (除了二维码 还需要其他信息)

            Map<String,Object> map = new HashMap<>();
            map.put("out_trade_no", orderNo);
            map.put("course_id", order.getCourseId());
            map.put("total_fee", order.getTotalFee());
            map.put("result_code", resultMap.get("result_code"));
            map.put("code_url", resultMap.get("code_url"));//wx支付的二维码

            //微信支付二维码2小时过期，可采取2小时未支付取消订单
            //redisTemplate.opsForValue().set(orderNo, map, 120, TimeUnit.MINUTES);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            throw new QLLException(ResultCode.ERROR.getCode(),"生成二维码失败");
            //return new HashMap<>();
        }
    }

    /**
     * 更新订单状态
     * @param map
     */
    @Override
    public void updateOrderStatus(Map<String, String> map) {
        //获取订单id
        String orderNo = map.get("out_trade_no");
        //根据订单id查询订单信息
        QueryWrapper<TOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no",orderNo);
        TOrder order = orderService.getOne(wrapper);

        if(order.getStatus().intValue() == OrderStatus.PAYED.getCode()) return;
        //修改订单支付状态
        order.setStatus( OrderStatus.PAYED.getCode());
        if(map.get("pay_type").equals("2"))order.setPayType(OrderPayType.ZFB.getCode());
        orderService.updateById(order);

        //记录支付日志
        TPayLog payLog=new TPayLog();
        payLog.setOrderNo(order.getOrderNo());//支付订单号
        payLog.setPayTime(new Date());
        if(map.get("pay_type").equals("1")){
            payLog.setPayType(OrderPayType.WX.getCode());//支付类型
        }else{
            payLog.setPayType(OrderPayType.ZFB.getCode());//支付类型
        }
        payLog.setTotalFee(order.getTotalFee());//总金额(分)
        payLog.setTradeState(map.get("trade_state"));//支付状态
        payLog.setTransactionId(map.get("transaction_id"));
        payLog.setAttr(JSONObject.toJSONString(map));
        baseMapper.insert(payLog);//插入到支付日志表
    }

    @Override
    public Map<String, Object> createNativeByAlipay(String orderNo) {

        AlipayTradePrecreateResponse  response;
        Map<String,Object> map=new HashMap<>();
        //根据订单id获取订单信息
        QueryWrapper<TOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no",orderNo);
        TOrder order = orderService.getOne(wrapper);
        try {
            response = Factory.Payment.FaceToFace()
                    //选择网页支付平台
                    //调用支付方法，设置订单名称、我们自己系统中的订单号、金额、回调页面3
                    .preCreate(order.getCourseTitle() , order.getOrderNo(),order.getTotalFee()+"");

            if (ResponseChecker.success(response)) {
                //System.out.println(response.getQrCode());
                map.put("code_url",response.getQrCode());
                map.put("course_id",order.getCourseId());
                map.put("out_trade_no",order.getOrderNo());
                map.put("result_code","SUCCESS");
                map.put("total_fee",order.getTotalFee()+"");
            } else {
                System.out.println("调用失败，原因" + response.msg);
                System.out.println("调用失败，原因" + response.subMsg);
            }
            //这里的response.body，就是一个可以直接加载的html片段，
            // 这里为了简单我直接返回这个片段，前端直接
        } catch (Exception e) {
            e.printStackTrace();
            throw new QLLException(20001,"申请二维码失败");
        }
        return map;
    }

    @Override
    public Map<String, String> queryPayStatusByAlipay(String orderNo) {
        AlipayTradeQueryResponse query=null;
        Map<String, String> map=new HashMap<>();
        try {
            query = Factory.Payment.Common().query(orderNo);
            System.out.println(query);
            map.put("out_trade_no",orderNo);
            map.put("pay_type", OrderPayType.ZFB.getCode()+"");
            map.put("trade_state", query.getTradeStatus());
            map.put("transaction_id", query.getTradeNo());
            //未支付tradeStatus:WAIT_BUYER_PAY
            //已支付tradeStatus:TRADE_SUCCESS
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }


    /**
     * 查询wx订单状态
     * @param orderNo
     * @return
     */
    @Override
    public Map queryPayStatus(String orderNo) {
        try {
            //1、封装参数
            Map m = new HashMap<>();
            m.put("appid", ConstantPropertiesUtils.PAY_APPID);
            m.put("mch_id", ConstantPropertiesUtils.PAY_PARTNER);
            m.put("out_trade_no", orderNo);
            m.put("nonce_str", WXPayUtil.generateNonceStr());

            //2、设置请求
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            client.setXmlParam(WXPayUtil.generateSignedXml(m, ConstantPropertiesUtils.PAY_PARTNERKEY));
            client.setHttps(true);
            client.post();
            //3、返回第三方的数据
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            resultMap.put("pay_type", OrderPayType.WX.getCode()+"");
            //6、转成Map
            //7、返回
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
